package com.dxy.common.user;

import com.dxy.common.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    /**
     * 解析token中用户信息放入ThreadLocal中
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(JwtUtil.TOKEN_NAME);
        System.out.println("token: " + token);
        AuthUserSubject subject = StringUtils.isNotBlank(token) ? JwtUtil.getSubject(token, AuthUserSubject.class) : null;
        UserContextHolder.setAuthUserSubject(subject);
        return true;
    }

    /**
     * 删除ThreadLocal防止内存泄漏
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.remove();
    }
}
